<template>
	<view class="info-popup">
		<view class="info-popup-con">
			<view class="info-popup-con-head">
				<view class="info-popup-con-head-title">回收确认</view>
				<view class="info-popup-con-head-close" @click="closeInfoPopup()"><uni-icons type="closeempty" size="22"
						color="#fff"></uni-icons></view>
			</view>
			<view class="info-popup-con-body">
				<view class="info-popup-con-body-left">
					<image class="info-popup-con-body-left-img" :src="material.picture"
						:mode="hasZipImage ? 'scaleToFill' : 'aspectFill'"></image>
				</view>
				<view class="info-popup-con-body-right">
					<view class="info-popup-con-body-right-item">
						<text class="info-popup-con-body-right-item-title">品牌：</text>
						<text
							class="info-popup-con-body-right-item-value">{{ material.brand ? material.brand : '-' }}</text>
					</view>
					<view class="info-popup-con-body-right-item">
						<text class="info-popup-con-body-right-item-title">型号：</text>
						<text
							class="info-popup-con-body-right-item-value">{{ material.specifications ? material.specifications : '-' }}</text>
					</view>
					<view class="info-popup-con-body-right-item">
						<text class="info-popup-con-body-right-item-title">物料编码：</text>
						<text
							class="info-popup-con-body-right-item-value">{{ material.number ? material.number : '-' }}</text>
					</view>

				</view>
			</view>
			<view class="info-popup-con-store" v-if="recoveryStoreList.length">
				<uni-data-select placeholder="选择回收仓" :localdata="recoveryStoreList" :clear="false"
					@change="recoveryStoreChange"></uni-data-select>
			</view>
			<view class="info-popup-con-print" @click="selectPrint = !selectPrint" v-if="false">
				<text class="info-popup-con-print-title">打印</text>
				<view class="info-popup-con-print-select"><uni-icons v-if="selectPrint" type="checkmarkempty"
						size="14"></uni-icons></view>
			</view>
			<view class="info-popup-con-stock">
				<view class="info-popup-con-stock-con">
					<view class="info-popup-con-stock-con-name">
						<text class="info-popup-con-stock-con-name-value">{{ material.material_name }}</text>
						<!-- <text class="info-popup-con-stock-con-track-value">货道:{{ material.st_name }}-{{ material.identification }}</text> -->
					</view>
					<view class="info-popup-con-stock-con-track">
						<text class="info-popup-con-stock-con-track-title">货道:</text>
						<text class="info-popup-con-stock-con-track-value">
							{{ material.st_name }}-{{ material.custom_identification ? material.custom_identification : material.identification }}
						</text>

					</view>

					<view class="info-popup-con-stock-con-num">
						<text class="info-popup-con-stock-con-num-title">回收数量：</text>
						<input class="info-popup-con-stock-con-num-inp" type="number" v-model="infoPopupNum" />
						<view class="info-popup-con-stock-con-num-replace" @click="replace = !replace">
							<text class="info-popup-con-stock-con-num-replace-title">以旧换新</text>
							<view class="info-popup-con-stock-con-num-replace-select"><uni-icons v-if="replace"
									type="checkmarkempty" size="14px"></uni-icons></view>
						</view>
					</view>
				</view>
				<view class="info-popup-con-stock-submit" @click="submit()">
					<text class="info-popup-con-stock-submit-text">提交</text>
				</view>
			</view>
		</view>
		<uni-popup ref="alertDialog" type="center">
			<uni-popup-dialog type="warning" :showClose="false" confirmText="领取完成" title="温馨提示" :content='content2'
				@confirm="closeTakeFinishPopup()"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	const API = require('../../../utils/apiConfig.js');
	export default {
		name: 'info-popup',
		props: {
			material: {
				type: Object,
				default: () => {
					return {};
				}
			},
			recoveryStoreList: {
				type: Array,
				default: () => {
					return [];
				}
			},
			isWeightCabinet: {
				type: Boolean,
				default: () => {
					return false;
				}
			}
		},
		data() {
			return {
				infoPopupNum: 0, //回收数量
				takelogId: '', //回收记录id,一起打印到二维码上
				selectPrint: true, //选择打印
				useOldReplaceNew: false, //是否使用以旧换新
				replace: false, //以旧换新
				hasRecoveryCabinet: false, //是否有回收柜
				weight3: 0, //回收柜3的初始重量（用01的称重器地址会与步进电机驱动器产生指令冲突,目前认为客户最多两台弹簧柜占用1和2）
				weight4: 0, //回收柜4的初始重量
				selectRecoveryStore: '', //选择的回收仓
				hasClickSubmit: false, //防止重复提交
				pageActive: true,
				navigateBackTimer: null, //提交完成提示返回定时器
				useNumber: '0',
				content2: '请在取出物品后点击“领取完成”按钮',
				switchTakeDoorTimerList: [], //自动关门的定时器数组
				hasZipImage: false,
			};
		},

		async mounted() {
			this.infoPopupNum = this.material.opnum;
			this.useOldReplaceNew = getApp().globalData.useOldReplaceNew;
			let hasRecoveryCabinetStorage = uni.getStorageSync('hasRecoveryCabinet');
			let saveReplace = uni.getStorageSync('hasReplace');
			this.replace = saveReplace ? true : false;
			this.hasRecoveryCabinet = hasRecoveryCabinetStorage ? true : false;
			uni.$on('messageMqtt', this.mqttMsg);
		},
		methods: {
			async closeTakeFinishPopup() {
				this.closeInfoPopup();
			},
			recoveryStoreChange(e) {
				console.log('选择回收仓==', e);

			},

			// 提交回收物料
			async submit() {
				let curSelectMaterial = JSON.parse(JSON.stringify(this.material));
				if (this.infoPopupNum < 1) {
					uni.showToast({
						title: '非法数量',
						icon: 'none'
					});
					return;
				}
				if (this.hasClickSubmit) {
					console.log('请勿重复提交');
					uni.showToast({
						title: '请勿重复提交',
						icon: 'none'
					});
					return;
				}
				if (this.infoPopupNum > curSelectMaterial.opnum) {
					uni.showToast({
						title: '超出可回收数量',
						icon: 'none'
					});
					this.hasClickSubmit = false;
					return;
				}
				this.hasClickSubmit = true;
				API.takerecovery({
					id: curSelectMaterial.man_id, //货道id
					recoverycargo_id: this.selectRecoveryStore.id, //回收货道id
					num: this.infoPopupNum, //数量
					identification: curSelectMaterial.identification, //货道标识
					// model_code: curSelectMaterial.model_code //模型号
					material_id: curSelectMaterial.id, //物料id
					return_id: curSelectMaterial.return_id, //回收id
					number: Number(this.useNumber)
				}).then((res) => {
					this.hasClickSubmit = false;
					if (res.code == 0) {
						this.$emit('recoveryFinish', curSelectMaterial.return_id, this.takelogId, this
							.infoPopupNum);
						this.$emit('updateRecoveryStoreList');
						if (this.replace) {
							this.replace = false;
							this.takeReplaceMaterial();
						} else {
							this.closeInfoPopup();
						}

					}
				})
			},

			async takeReplaceMaterial() {
				let curMaterialTotalNum = 0; //当前物料在所有货道加起来的总库存数量
				let curMaterialList = []; //当前物料所在的所有货道列表(所有柜子加起来)
				let res = await API.managementlist({
					material_id: this.material.id
				});
				console.log("kym     =====>>>>   " + JSON.stringify(res));
				for (let i = 0; i < res.data.length; i++) {
					// 获取当前物料在当前货柜的库存总数
					let curMaterialNumForCabinet = res.data[i].management.reduce((accumulator, obj) => accumulator +
						Number(
							obj.now_num), 0);
					console.log(`物料[${this.material.material_name}]在[${res.data[i].st_name}]的库存总数==`,
						curMaterialNumForCabinet);
					// 遍历当前货柜的所有货道,设置额外需要的基础参数变量
					for (let j = 0; j < res.data[i].management.length; j++) {
						// console.log('management==', res[i].management[j]);
						res.data[i].management[j].st_name = res.data[i].st_name;
						res.data[i].management[j].registeras = res.data[i].registeras;
						res.data[i].management[j].is_direction = res.data[i].is_direction;
						res.data[i].management[j].material_name = this.material.material_name;
						res.data[i].management[j].material_id = this.material.id;
						// 累加所有货柜的所有货道，计算当前物料可取数量总数
						curMaterialTotalNum += res.data[i].management[j].now_num;
						// 整合当前物料所有货道列表
						curMaterialList = curMaterialList.concat(res.data[i].management[j]);
					}
				}
				console.log(`当前物料的所有货道==`, curMaterialList);
				console.log(`当前物料可领取数量==${curMaterialTotalNum}`);
				if (curMaterialList.length && curMaterialTotalNum > 0) {
					let model = curMaterialList[0].model_code;
					let direction = curMaterialList[0].is_direction;
					let reg = curMaterialList[0].registeras;
					let y = curMaterialList[0].identification.split('-')[0];
					let x = curMaterialList[0].identification.split('-')[1];
					let num = 1;
					try {
						let res = await API.take({
							id: curMaterialList[0].id, //货道id
							num: num, //数量
							identification: curMaterialList[0].identification, //货道标识
							machinetool_id: '', //集合
							model_code: curMaterialList[0].model_code, //模型号
							productnum: '', //产线号
							custom_arr: '',
							custom_gather: ''
						});
						this.openTrackForReplace(model, direction, reg, y, x, num);
					} catch (e) {
						console.log('取料错误==', e);
					}
				} else {
					uni.hideLoading();
					this.closeInfoPopup();
					uni.$emit('speech', '请将归还物料放至所选的货道');
					uni.showToast({
						title: '请将归还物料放至所选的货道',
						icon: 'none'
					});
					uni.showModal({
						title: '温馨提示',
						content: '库存不足,无法以旧换新',
						showCancel: false
					});
				}
			},
			async openTrackForReplace(model, direction, reg, y, x, num) {
				console.log({
					model,
					direction,
					reg,
					y,
					x,
					num
				});
				this.send(num, (y - 1) * 10 + x);
			},
			closeInfoPopup() {
				this.hasClickSubmit = false;
				this.infoPopupNum = 0;
				this.$emit('closeInfoPopup');
			},
			send(num, y) {
				if (!getApp().globalData.mqttClient || !getApp().globalData.mqttClient.connected) {
					console.log('MQTT not connected');
					return Promise.reject('MQTT not connected');
				}
				let timestamp = new Date().getTime();
				const payload = JSON.stringify({
					c: 22,
					f: 'ZHZN002',
					t: '868999061201244',
					m: `1,${y}&${num}`,
					s: `${timestamp}`,
					mi: 2
				});
				getApp().globalData.mqttClient.publish('ZHZN/868999061201244', payload, (err) => {
					if (err) {
						console.log('publish error: ' + err.message);

					} else {
						console.log('message sent: ' + payload);
					}

				});
			},
			mqttMsg(topic, msg) {
				console.log("topic is " + topic);
				console.log("message is " + msg);
				this.closeInfoPopup();
			}

		},
		destroyed() {
			// console.log('组件销毁');
			clearTimeout(this.navigateBackTimer);
			this.pageActive = false;
			uni.$off('messageMqtt', this.mqttMsg);
			for (let i = 0; i < this.switchTakeDoorTimerList.length; i++) {
				clearTimeout(this.switchTakeDoorTimerList[i]);
			}
		}
	};
</script>

<style lang="scss">
	.info-popup {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: 998;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: rgba(0, 0, 0, 0.4);

		.info-popup-con {
			// position: absolute;
			// top: 20vh;
			width: 500rpx;
			max-width: 600px;
			border-radius: 12px;
			overflow: hidden;
			background-color: #ffffff;

			.info-popup-con-head {
				margin-bottom: 5px;
				position: relative;
				height: 64rpx;
				display: flex;
				flex-direction: row;
				justify-content: center;
				align-items: center;
				background-color: #333847;

				.info-popup-con-head-title {
					font-size: 26rpx;
					color: #fff;
					font-weight: bold;
				}

				.info-popup-con-head-close {
					position: absolute;
					right: 0;
					top: 0;
					padding: 16rpx;
				}
			}

			.info-popup-con-body {
				padding: 20rpx;
				display: flex;
				flex-direction: row;
				align-items: center;

				.info-popup-con-body-left {
					display: flex;
					flex-direction: column;

					.info-popup-con-body-left-img {
						max-width: 180rpx;
						max-height: 180rpx;
						width: 150px;
						height: 150px;
						display: block;
						overflow: hidden;
						border-radius: 6px;
						box-shadow: 1px 2px 2px 2px rgba(0, 0, 0, 0.1);
					}
				}

				.info-popup-con-body-right {
					flex: 1;
					height: 120px;
					max-height: 150rpx;
					padding-left: 15px;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.info-popup-con-body-right-item {
						padding: 5px 0;
						display: flex;
						flex-direction: row;
						align-items: center;
						border-bottom: 1px solid #eee;
						justify-content: space-between;

						.info-popup-con-body-right-item-title {
							font-size: 20rpx;
							line-height: 18px;
							height: 18px;
							flex-shrink: 0;
						}

						.info-popup-con-body-right-item-value {
							// text-align: right;
							word-break: break-all;
							font-size: 20rpx;
							line-height: 18px;
							height: 18px;
						}
					}
				}
			}

			.info-popup-con-store {
				padding: 0 20px;
				margin-bottom: 10px;

				::v-deep .uni-select {
					height: 50px;

					.uni-select__input-box {
						height: 50px;

						.uni-select__input-placeholder {
							font-size: 18px;
						}
					}

					.uni-select__selector {
						.uni-select__selector-item {
							font-size: 18px;
						}
					}
				}
			}

			.info-popup-con-print {
				padding: 0 20px;
				height: 28rpx;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;

				.info-popup-con-print-title {
					font-size: 20rpx;
					line-height: 18px;
					height: 18px;
				}

				.info-popup-con-print-select {
					width: 18rpx;
					height: 18rpx;
					// background-color: #ffffff;
					border: 1px solid #aaa;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
				}
			}

			.info-popup-con-stock {
				padding: 20rpx;

				.info-popup-con-stock-con {
					padding: 10px;
					border-radius: 4px;
					border: 1px solid #eee;
					background-color: #f5f5f5;

					.info-popup-con-stock-con-name {
						display: flex;
						flex-direction: row;
						justify-content: space-between;

						.info-popup-con-stock-con-name-value {
							font-size: 26rpx;
							font-weight: bold;
						}
					}

					.info-popup-con-stock-con-track {
						margin-top: 10rpx;
						display: flex;
						flex-direction: row;
						justify-content: space-between;

						.info-popup-con-stock-con-track-title {
							font-size: 26rpx;
							color: #555;
						}

						.info-popup-con-stock-con-track-value {
							font-size: 26rpx;
							color: #555;
						}
					}

					.info-popup-con-stock-con-num {
						margin-top: 8px;
						display: flex;
						flex-direction: row;
						align-items: center;

						.info-popup-con-stock-con-num-title {
							font-size: 26rpx;
							color: #555;
							flex-shrink: 0;
						}

						.info-popup-con-stock-con-num-inp {
							flex: 1;
							height: 40rpx;
							box-sizing: border-box;
							padding: 0 10px;
							border: 1px solid #eee;
							font-size: 26rpx;
							background-color: #ffffff;
						}

						.info-popup-con-stock-con-num-replace {
							padding-left: 10px;
							height: 20px;
							display: flex;
							flex-direction: row;
							justify-content: space-between;
							align-items: center;

							.info-popup-con-stock-con-num-replace-title {
								color: #555;
								font-size: 26rpx;
								line-height: 18px;
								height: 18px;
							}

							.info-popup-con-stock-con-num-replace-select {
								width: 12px;
								height: 12px;
								margin-left: 4px;
								// background-color: #ffffff;
								border: 1px solid #aaa;
								display: flex;
								flex-direction: column;
								justify-content: center;
								align-items: center;
							}
						}

						.info-popup-con-stock-con-num-btns {
							display: flex;
							flex-direction: row;

							.info-popup-con-stock-con-num-btns-item {
								width: 40px;
								height: 40px;
								box-sizing: border-box;
								border: 1px solid #fff;
								margin-left: 5px;
								border-radius: 2px;
								display: flex;
								flex-direction: column;
								justify-content: center;
								align-items: center;
								color: #ffffff;
								font-size: 26rpx;
								background-color: #333847;

								&.full {
									font-size: 18px;
								}
							}
						}
					}
				}

				.info-popup-con-stock-submit {
					height: 64rpx;
					margin-top: 10px;
					border-radius: 6px;
					display: flex;
					flex-direction: row;
					justify-content: center;
					align-items: center;
					background-color: #333847;

					&:active {
						background-color: #695f48;
					}

					.info-popup-con-stock-submit-text {
						color: #ffffff;
						font-size: 26rpx;
					}
				}
			}
		}
	}
</style>